﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Serialization;

namespace LuckStar
{

    /// <summary>
    /// 抽奖操作类
    /// </summary>
    public class LuckAction
    {
        private static readonly string settingFile = "setting.xml";
        private static readonly string userFile = "名单.txt";
        private static readonly string imagedir = "images";

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <returns></returns>
        public static Lucky LoadData()
        {
            Lucky luck;
            if (File.Exists(settingFile) == false)
            {
                luck = new Lucky();
                SaveData(luck);
                return luck;
            }   
            XmlSerializer serializer = new XmlSerializer((new Lucky()).GetType());
            using (FileStream stream = new FileStream(settingFile, FileMode.Open))
            {
                luck = (Lucky)serializer.Deserialize(stream);
                stream.Close();
               
            }
            luck.PrizeList = luck.PrizeList.OrderBy(c=>c.SortID).ToList<Prize>();//排序
            luck = LoadUserData(luck);//加载用户          
            return luck;
        }

        /// <summary>
        /// 加载用户
        /// </summary>
        /// <param name="luck"></param>
        /// <returns></returns>
        public static Lucky LoadUserData(Lucky luck)
        {
            luck.UserList.Clear();
            if (File.Exists(userFile))//加载用户
            {
                string[] str = File.ReadAllLines(userFile);
                string tmp;
                foreach (string s in str)
                {
                    tmp = s.Trim().Replace("  ", " ");
                    if (luck.UserList.Contains(tmp) == false)
                        luck.UserList.Add(tmp);
                }
            }
            return luck;
        }

        /// <summary>
        /// 删除一个奖项
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static bool DelPrize(string pid)
        {
            Lucky luck = LoadData();
            foreach(Prize p in luck.PrizeList)
            {
                if (p.guid == pid)
                {
                    luck.PrizeList.Remove(p);
                    break;
                }
            }
            SaveData(luck);
            return true;
        }
        /// <summary>
        /// 保存一个奖项
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static bool SavePrize(Prize pri)
        {
            Lucky luck = LoadData();
            if (string.IsNullOrEmpty(pri.guid))
            {//新增
                pri.guid = Guid.NewGuid().ToString();
                if (string.IsNullOrEmpty(pri.Image) == false)
                {
                    pri.Image = CopyPic(pri.guid, pri.Image);
                }
                luck.PrizeList.Add(pri);
            }//if
            else//修改
            {
                foreach (Prize p in luck.PrizeList)
                {
                    if (p.guid == pri.guid)
                    {
                        p.SortID = pri.SortID;
                        p.Name = pri.Name;
                        p.PrizeName = pri.PrizeName;
                        if (string.IsNullOrEmpty(pri.Image) == false)
                        {
                            p.Image = CopyPic(p.guid, pri.Image);
                        }
                        else
                        {
                        p.Image = pri.Image;
                        }
                        p.IsExclude = pri.IsExclude;
                        p.Count = pri.Count;
                        break;
                    }
                }//foreach
            } //else         
            SaveData(luck);
            return true;
        }

        /// <summary>
        /// 移动图片文件
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="picUrl"></param>
        /// <returns></returns>
        private static string  CopyPic(string guid,string picUrl)
        {
            if (File.Exists(picUrl) == false)//不存在的就保存为不存在
            {
                return "";
            }
            string path = Path.Combine(imagedir, guid + Path.GetExtension(picUrl));
            if (picUrl == path)
                return picUrl;
            string fullpath = Path.GetFullPath(path);            
            string dir = Path.GetDirectoryName(fullpath);
            if (Directory.Exists(dir) == false)
                Directory.CreateDirectory(dir);
            try
            {
                if (File.Exists(fullpath))
                {
                    File.Delete(fullpath);
                }
                File.Copy(picUrl, fullpath);
            }
            catch
            {
                ;
            }
            return path;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        public static bool SaveData(Lucky data)
        {
            if (string.IsNullOrEmpty(data.BackgroudImage) == false)
            {
                data.BackgroudImage = CopyPic("bg", data.BackgroudImage);
            }
             XmlSerializer serializer = new XmlSerializer(data.GetType());
            using (TextWriter writer = new StreamWriter(settingFile))
            {
                serializer.Serialize(writer, data);
                writer.Close();
            }             
            return true;
        }
        /// <summary>
        /// 清除并保存已经中奖的数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static Lucky ClearData(Lucky data,string guid="", bool IsClearUser = false)
        {
            if (string.IsNullOrEmpty(guid)==false)
            {
                foreach (Prize p in data.PrizeList)
                {
                    if (p.guid == guid)
                    {
                        p.WinnersList.Clear();
                        break;
                    }
                }
            }
            else
            {
                foreach (Prize p in data.PrizeList)
                {
                    p.WinnersList.Clear();
                }
            }            
            if (IsClearUser)
                data.UserList.Clear();
            SaveData(data);
            return data;
        }

        /// <summary>
        /// 获取未中奖的用户
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<string> GetUnWinnersList(Lucky data)
        {
            List<string> list = new List<string>();
            foreach(string u in data.UserList)
            {
                if (IsWinners(u, data) == false)//如果没中奖的，就取出来
                {
                    list.Add(u);
                }
            }
            return list.OrderBy(c=>Guid.NewGuid()).ToList<string>();
        }
        /// <summary>
        /// 随机显示几个用户
        /// </summary>
        /// <param name="users"></param>
        /// <param name="uCount"></param>
        /// <returns></returns>
        public static List<string> GetRandomUser(List<string> users,int uCount)
        {
            users= users.OrderBy(c => Guid.NewGuid()).ToList<string>();
            if (users.Count < uCount)
                return users;
            while (users.Count > uCount)
            {
                users.RemoveAt(0);
            }
            return users;
        }
        /// <summary>
        /// 判断一个人是否已经中过奖了
        /// </summary>
        /// <param name="user"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private static bool IsWinners(string user, Lucky data)
        {
            bool isW = false;
            foreach(Prize p in data.PrizeList)
            {
                if (p.IsExclude)//互斥的奖项
                {
                    if (p.WinnersList.Contains(user))//已经中奖了
                    {
                        isW = true;
                        break;
                    }
                }
            }
            return isW;
        }
        /// <summary>
        /// 保存抽奖记录
        /// </summary>
        /// <param name="data"></param>
        /// <param name="PrizeID"></param>
        /// <returns></returns>
        public static Lucky SaveLuck(Lucky data,string PrizeID,List<string> WinnersList)
        {
            foreach (Prize p in data.PrizeList)
            {
                if (p.guid == PrizeID)
                {
                    foreach(string newu in WinnersList)
                    {
                        p.WinnersList.Add(newu);
                    }
                }
            }
            return data;
        }

    }

    /// <summary>
    /// 抽奖主体
    /// </summary>
   public class Lucky
    {
        /// <summary>
        /// 标题
        /// </summary>
        public string Title = "幸运星抽奖程序";
        
        /// <summary>
        /// 背景图片
        /// </summary>
        public string BackgroudImage = "bg.jpg";
        /// <summary>
        /// 员工名单列表
        /// </summary>
        public List<string> UserList = new List<string>();
        /// <summary>
        /// 奖项列表
        /// </summary>
        public List<Prize> PrizeList = new List<Prize>();

    }

    /// <summary>
    /// 奖项名称
    /// </summary>
    public class Prize
    {
        /// <summary>
        /// 系统ID
        /// </summary>
        public string guid = Guid.NewGuid().ToString();
        /// <summary>
        /// 排序ID
        /// </summary>
        public int SortID = 0;
        /// <summary>
        /// 奖项名称
        /// </summary>
        public string Name = "";
        /// <summary>
        /// 奖品名称
        /// </summary>
        public string PrizeName = "";
        /// <summary>
        /// 奖品图片
        /// </summary>
        public string Image = "";       
        /// <summary>
        /// 中奖人数
        /// </summary>
        public int Count = 0;       
        /// <summary>
        /// 是否互斥
        /// 本次中奖后其他奖项不能再中奖
        /// </summary>
        public bool IsExclude = true;
        /// <summary>
        /// 已经中奖的名单
        /// </summary>
        public List<string> WinnersList = new List<string>();

    }


}
